package com.ruoyi.utils.aly;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.*;
import com.aliyun.tea.TeaException;
import com.ruoyi.SSL.domain.SslApply;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * /api/v1/providers/Aliyun/products/OSS/resources/Bucket
 * 阿里云oss对象存储https证书配置类
 */
public class AlyOssDomianApiUtils {

    /**
     * 创建OSS客户端
     * @param accessKeyId keyId
     * @param accessKeySecret 秘钥
     * @param endpoint 请求地址
     * @param region 地域
     */
    public static OSS ossClientCreate(String accessKeyId, String accessKeySecret, String endpoint, String region){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        endpoint = StrUtil.isBlank(endpoint)?"https://oss-cn-hangzhou.aliyuncs.com":endpoint;
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        region = StrUtil.isBlank(region)?"cn-hangzhou":region;
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        return OSSClientBuilder.create().endpoint(endpoint).credentialsProvider(credentialsProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();
    }

    /**
     * 查询阿里云OSS域名列表
     * @param accessKeyId 阿里云keyId
     * @param accessKeySecret 阿里云秘钥
     */
    public static AjaxResult selectBuchetsCNameList(String accessKeyId, String accessKeySecret){
        try {
            //得到OSS对象信息
            OSS ossClient = ossClientCreate(accessKeyId, accessKeySecret, null, null);
            List<Bucket> buckets = ossClient.listBuckets();
            List<JSONObject> cnameConfigurationList = new ArrayList<>();
            //循环获取到域名信息
            for (Bucket bucket : buckets) {
                ossClient = ossClientCreate(accessKeyId, accessKeySecret, bucket.getExtranetEndpoint(), bucket.getRegion());
                List<JSONObject> cnameConfigurations = JSONUtil.toList(JSONUtil.toJsonStr(ossClient.getBucketCname(bucket.getName())), JSONObject.class);
                for (JSONObject cnameConfiguration : cnameConfigurations) {
                    cnameConfiguration.set("bucket", bucket);
                }
                cnameConfigurationList.addAll(cnameConfigurations);
            }
            //返回数据
            return AjaxResult.success("查询阿里云OSS域名成功", cnameConfigurationList);
        } catch (Exception _error) {
            return AjaxResult.error("查询阿里云OSS域名失败："+_error.getMessage());
        }
    }

    /**
     * 设置OSS域名证书
     * @param accessKeyId 阿里云keyId
     * @param accessKeySecret 阿里云秘钥
     * @param sslApply 证书申请对象
     * @param bucket 操作桶对象
     * @param domain 操作域名
     */
    public static AjaxResult putCnameSSL(String accessKeyId, String accessKeySecret,SslApply sslApply,Bucket bucket, String domain){
        try {
            OSS ossClient = ossClientCreate(accessKeyId, accessKeySecret, bucket.getExtranetEndpoint(), bucket.getRegion());
            // 添加CNAME记录。
            AddBucketCnameRequest request = new AddBucketCnameRequest(bucket.getName());
            request.setDomain(domain);
            CertificateConfiguration certificateConfiguration = new CertificateConfiguration();
            certificateConfiguration.setId("16524459");
            request.setCertificateConfiguration(certificateConfiguration);
            //得到请求结果
            AddBucketCnameResult cnameResult = ossClient.addBucketCname(request);
            Console.log(JSONUtil.toJsonStr(cnameResult));
            if(cnameResult.getResponse().getStatusCode() == 200){
                return AjaxResult.success("配置阿里云OSS域名证书成功！", cnameResult.getCertId());
            }else{
                return AjaxResult.error("配置阿里云OSS域名证书失败："+JSONUtil.toJsonStr(cnameResult.getResponse()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("配置阿里云OSS域名证书错误："+e.getMessage());
        }
    }
}
